package com.iotechn.uninotify.service.biz;

import com.alibaba.fastjson.JSONObject;
import com.iotechn.uninotify.compent.CacheComponent;
import com.iotechn.uninotify.exception.NotifyExceptionDefinition;
import com.iotechn.uninotify.exception.NotifyServiceException;
import com.iotechn.uninotify.exception.ServiceException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: rize
 * Date: 2019/12/26
 * Time: 18:00
 */
@Service
public class WxMpBizService {

    private static final String CA_WXMP_ACCESS_TOKEN = "CA_OFFICIAL_WECHAT_ACCESS";

    @Value("${com.iotechn.uninotify.mp.app-id}")
    private String appId;

    @Value("${com.iotechn.uninotify.mp.app-secret}")
    private String appSecret;

    private OkHttpClient okHttpClient = new OkHttpClient();

    @Autowired
    private CacheComponent cacheComponent;

    /**
     * 获取公众号AccessToken
     * @return
     */
    public String getAccessToken() throws ServiceException {
        try {
            String access_token = cacheComponent.getRaw(CA_WXMP_ACCESS_TOKEN);
            if (StringUtils.isEmpty(access_token)) {
                String accessJson = okHttpClient.newCall(
                        new Request.Builder()
                                .url("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + this.appId + "&secret=" + this.appSecret)
                                .get()
                                .build()).execute().body().string();
                JSONObject jsonObject = JSONObject.parseObject(accessJson);
                access_token = jsonObject.getString("access_token");
                if (!StringUtils.isEmpty(access_token)) {
                    Integer expires_in = jsonObject.getInteger("expires_in");
                    Integer cacheExpireSec = expires_in * 4 / 5;
                    cacheComponent.putRaw(CA_WXMP_ACCESS_TOKEN, access_token, cacheExpireSec);
                } else {
                    throw new RuntimeException("回复错误:" + accessJson);
                }
            }
            return access_token;
        } catch (IOException e) {
            throw new NotifyServiceException(NotifyExceptionDefinition.NOTIFY_IO_EXCEPTION);
        }
    }

}
